const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const Package = require('./Package');
const Tag = require('./Tag');

// 定义PackageTag模型（包和标签的关联表）
const PackageTag = sequelize.define('PackageTag', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  package_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: Package,
      key: 'id'
    },
    comment: '包ID'
  },
  tag_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: Tag,
      key: 'id'
    },
    comment: '标签ID'
  }
}, {
  tableName: 'package_tags',
  indexes: [
    { name: 'idx_package_tag', fields: ['package_id', 'tag_id'], unique: true }
  ]
});

// 建立多对多关系
Package.belongsToMany(Tag, {
  through: PackageTag,
  foreignKey: 'package_id',
  otherKey: 'tag_id',
  as: 'tags'
});

Tag.belongsToMany(Package, {
  through: PackageTag,
  foreignKey: 'tag_id',
  otherKey: 'package_id',
  as: 'packages'
});

module.exports = PackageTag;